package edu.westga.sketchit2009cs.network;

/*************************************************************************
 *  Compilation:  javac ChatServer.java 
 *  Execution:    java ChatServer
 *  Dependencies: In.java Out.java Connection.java ConnectionListener.java
 *
 *  Creates a server to listen for incoming connection requests on 
 *  port 4444.
 *
 *  % java ChatServer
 *
 *************************************************************************/

import java.io.IOException;
import java.net.Socket;
import java.net.ServerSocket;
import java.util.Vector;

public class ChatServer implements Runnable {
    private static Vector<Connection> connections;
    private static  ServerSocket serverSocket;

    public ChatServer(int portNumber) throws Exception {
        connections = new Vector<Connection>();
        serverSocket = new ServerSocket(portNumber);
        ConnectionListener connectionListener = new ConnectionListener(connections);

        // thread that broadcasts messages to clients
        connectionListener.start();
    }
    
	@Override
	public void run() {
        while (true) {

            // wait for next client connection request
        	Socket clientSocket = null;
			try {
				clientSocket = serverSocket.accept();
			} catch (IOException e) {
				e.printStackTrace();
			}

            // listen to client in a separate thread
            Connection connection = new Connection(clientSocket);
            connections.add(connection);
            connection.start();
        }
	}
}